package cn.jetpiece.cloud.joss.app.modular.accessor.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.jetpiece.cloud.joss.api.accossor.AccessorApi;
import cn.jetpiece.cloud.joss.api.accossor.model.params.CreateAccessorParam;
import cn.jetpiece.cloud.joss.api.accossor.model.params.UpdateAccessorParam;
import cn.jetpiece.cloud.joss.api.accossor.model.query.AccessorQuery;
import cn.jetpiece.cloud.joss.api.accossor.model.result.AccessorResult;
import cn.jetpiece.cloud.joss.api.constant.AccessorCache;
import cn.jetpiece.cloud.joss.app.modular.accessor.entity.Accessor;
import cn.jetpiece.cloud.joss.app.modular.accessor.service.AccessorService;
import cn.jetpiece.cloud.model.contants.ResponseMsgConstants;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * 授权控制器
 *
 * @author XuJZ
 * @since 2020-09-05 15:41:52
 */
@Slf4j
@RestController
public class AccessorController implements AccessorApi {

    @Autowired
    private AccessorService accessorService;

    @Override
    public Result<String> add(CreateAccessorParam param) {
        if (accessorService.add(param)) {
            return Result.OK(ResponseMsgConstants.CREATE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.CREATE_ERROR);
        }
    }

    @Override
    public Result<String> update(UpdateAccessorParam param) {
        if (accessorService.update(param)) {
            return Result.OK(ResponseMsgConstants.UPDATE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.UPDATE_ERROR);
        }
    }

    @Override
    public Result<String> delete(String id) {
        if (accessorService.delete(id)) {
            return Result.OK(ResponseMsgConstants.DELETE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.DELETE_ERROR);
        }
    }

    @Override
    public Result<AccessorCache> getByAccessKey(String accessKey) {
        return Result.OK(accessorService.getByAccessKey(accessKey));
    }

    @Override
    public Result<AccessorResult> get(String id) {
        Accessor bean = accessorService.getById(id);
        if (bean == null) {
            return Result.OK();
        }
        AccessorResult result = new AccessorResult();
        BeanUtil.copyProperties(bean, result);
        return Result.OK(result);
    }

    @Override
    public Result<PageResult<AccessorResult>> page(AccessorQuery query) {
        return Result.OK(accessorService.page(query));
    }

}
